"""
配置加载器 - 根据环境变量加载不同配置
"""
import os
from typing import Dict, Any
import yaml


class Settings:
    """配置管理器"""
    
    def __init__(self):
        self.env = os.getenv("ENVIRONMENT", "development")
        self._load_config()
    
    def _load_config(self):
        """加载配置文件"""
        config_file = f"config/{self.env}.yaml"
        
        if os.path.exists(config_file):
            with open(config_file, 'r', encoding='utf-8') as f:
                self.config = yaml.safe_load(f)
        else:
            # 默认配置
            self.config = {
                "database": {
                    "url": os.getenv("DATABASE_URL", "sqlite:///app.db"),
                    "echo": False
                },
                "api": {
                    "timeout": int(os.getenv("API_TIMEOUT", "30")),
                    "retry_times": int(os.getenv("API_RETRY_TIMES", "3"))
                },
                "logging": {
                    "level": os.getenv("LOG_LEVEL", "INFO"),
                    "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
                },
                "auth": {
                    "jwt_secret": os.getenv("JWT_SECRET_KEY", "default-secret-key"),
                    "token_expire_hours": int(os.getenv("TOKEN_EXPIRE_HOURS", "24"))
                }
            }
    
    def get(self, key: str, default: Any = None) -> Any:
        """获取配置值"""
        keys = key.split(".")
        value = self.config
        
        for k in keys:
            if isinstance(value, dict) and k in value:
                value = value[k]
            else:
                return default
        
        return value
    
    def __getitem__(self, key: str) -> Any:
        """支持字典式访问"""
        return self.get(key)


# 全局配置实例
settings = Settings()